//
//  ViewController.m
//  3.27、NSURLConnection基本使用
//
//  Created by 李坤 on 16/12/16.
//
//
/*
 NSURLConnection的差用类
 1、NSURL：请求地址
 2、NSURLRequest：封装一个请求，报错发给服务器的全部数据，包括一个NSURL对象，请求方法，请求头，请求体...
 3、NSMutableURLRequest：NSURLRequest的子类
 4、NSURLConnection：负责发送请求，建立客户端和服务器的链接，发送NSURLRequest的数据给服务器，并收集来自服务器的响应数据.
 */
#import "ViewController.h"
#import "BorrowModel.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
@property(nonatomic,strong)NSOperationQueue *queue;
@property(nonatomic,weak)UITableView *tv;
@property(nonatomic,strong)NSMutableArray<BorrowModel *> *borrowList;
//当前页数
@property(nonatomic,assign)int page;
//总页数
@property(nonatomic,assign)int pageCount;
//当前是否在加载数据
@property(nonatomic,assign)Boolean isLoad;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    [self t1];
    [self t2];
    [self load];
}

- (NSMutableArray<BorrowModel *> *)borrowList{
    if(_borrowList==nil){
        _borrowList = [NSMutableArray array];
    }
    return _borrowList;
}

- (NSOperationQueue *)queue{
    if(_queue==nil){
        _queue = [[NSOperationQueue alloc] init];
    }
    return _queue;
}


- (void)t3{
    BorrowModel *bm = [[BorrowModel alloc] init];
    bm.title = @"ready";
    void (^block1)() = ^{
//        NSLog(@"嘿嘿%@",bm);
    };
    bm = nil;
    NSLog(@"嘿嘿");
//    block1();
}


- (void)load{
    UITableView *tv = [[UITableView alloc] init];
    tv.frame = CGRectMake(0, [UIApplication sharedApplication].statusBarFrame.size.height+20, self.view.bounds.size.width, self.view.bounds.size.height - [UIApplication sharedApplication].statusBarFrame.size.height-20);
    tv.delegate = self;
    tv.dataSource = self;
    [self.view addSubview:tv];
    self.tv = tv;
    self.page = 1;
    self.pageCount = 1;
    self.isLoad = NO;
    [self loadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.borrowList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier  = @"borrow_cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if(cell==nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    BorrowModel *bm = [self.borrowList objectAtIndex:indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%lu、%@",bm.borrow_id,bm.title];
    cell.textLabel.textColor = [UIColor redColor];
    cell.detailTextLabel.text = [NSString stringWithFormat:@"金额：%@",bm.price];
    
    return cell;
}

- (void)loadData{
    //避免一个加载还未完成，另一个加载又来了
    if(!self.isLoad && self.page<=self.pageCount){
        self.isLoad = YES;
        [self.queue addOperation:[NSBlockOperation blockOperationWithBlock:^{
            //1.创建NSURL对象
            NSString *urlStr = [NSString stringWithFormat:@"http://api.yijiedai.com/invest?page=%i",self.page];
            urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSLog(@"urlStr = %@",urlStr);
            NSURL *url = [NSURL URLWithString:urlStr];
            //2.创建NSURLRequest对象
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
            request.HTTPMethod = @"GET";
            //    request.HTTPBody = [@"page=3" dataUsingEncoding:NSUTF8StringEncoding];
            //3.创建NSURLConnection对象，发送请求
            NSURLResponse *response;
            NSError *error;
            NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
            [NSURLConnection sendAsynchronousRequest:request queue:self.queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
                if(!connectionError){
                    id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                    NSArray<NSDictionary<NSString *,id> *> *dataList = result[@"data"][@"page"][@"dataList"];
                    NSMutableArray<BorrowModel *> *borrowList = [NSMutableArray array];
                    [dataList enumerateObjectsUsingBlock:^(NSDictionary<NSString *,id> * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        [borrowList addObject:[BorrowModel borrowWithDict:obj]];
                    }];
//                    NSLog(@"borrowList = %@",borrowList);
//                    NSLog(@"%@",[NSThread currentThread]);
//                    NSLog(@"%i",[result[@"data"][@"page"][@"count"] isKindOfClass:[NSNumber class]]);
                    NSNumber *pageCount =result[@"data"][@"page"][@"count"];
                    //通过主线程队列更新tableview数据
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self loadDataSuccess:borrowList andPageCount:pageCount.intValue];
                    });
                }
            }];
        }]];
    }
}

- (void)loadDataSuccess:(NSMutableArray<BorrowModel *> *)array andPageCount:(int)pageCount{
    self.pageCount = pageCount;
    [self.borrowList addObjectsFromArray:array];
    [self.tv reloadData];
    self.page++;
    self.isLoad = NO;
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if(self.tv.contentOffset.y+self.tv.bounds.size.height>=self.tv.contentSize.height-100){
        [self loadData];
    }
}

//异步发送数据
- (void)t2{
    //1.创建NSURL对象
    NSString *urlStr = [NSString stringWithFormat:@"http://api.yijiedai.com/invest?page=%i",3];
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"urlStr = %@",urlStr);
    NSURL *url = [NSURL URLWithString:urlStr];
    //2.创建NSURLRequest对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    //    request.HTTPBody = [@"page=3" dataUsingEncoding:NSUTF8StringEncoding];
    //3.创建NSURLConnection对象，发送请求
    NSURLResponse *response;
    NSError *error;
    NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue mainQueue] init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if(!connectionError){
            NSArray<NSDictionary<NSString *,id> *> *dataList = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil][@"data"][@"page"][@"dataList"];
            NSMutableArray<BorrowModel *> *borrowList = [NSMutableArray array];
            [dataList enumerateObjectsUsingBlock:^(NSDictionary<NSString *,id> * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [borrowList addObject:[BorrowModel borrowWithDict:obj]];
            }];
            NSLog(@"borrowList = %@",borrowList);
            NSLog(@"%@",[NSThread currentThread]);
        }else{
            self.isLoad = NO;
        }
    }];
    NSLog(@"加载数据");
}

//同步发送数据
- (void)t1{
    //1.创建NSURL对象
    NSString *urlStr = [NSString stringWithFormat:@"http://api.yijiedai.com/invest?page=%i",3];
    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"urlStr = %@",urlStr);
    NSURL *url = [NSURL URLWithString:urlStr];
    //2.创建NSURLRequest对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
//    request.HTTPBody = [@"page=3" dataUsingEncoding:NSUTF8StringEncoding];
    //3.创建NSURLConnection对象，发送请求
    NSURLResponse *response;
    NSError *error;
    NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
    if(error!=nil){
        NSLog(@"error = %@",[error localizedDescription]);
    }
    NSArray<NSDictionary<NSString *,id> *> * dataList = [[NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableLeaves error:&error] valueForKeyPath:@"data.page.dataList"];
    NSMutableArray<BorrowModel *> *borrowList = [NSMutableArray array];
    [dataList enumerateObjectsUsingBlock:^(NSDictionary<NSString *,id> * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [borrowList addObject:[BorrowModel borrowWithDict:obj]];
    }];
    NSLog(@"borrowList = %@",borrowList);
    NSLog(@"结果：%@",[[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding]);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
